package com.ssl.basics.unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * 描述：通过Unsafe实例化对象，即使对象的构造方法是私有的
 *
 * @author ssl
 * @create 2021/7/13 0013.
 */
public class UnsafeDemo {

    public static void main(String[] args) throws Exception {
        // 反射机制获取 Unsafe 实例
        Field field = Unsafe.class.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        Unsafe unsafe = (Unsafe) field.get(null);

        // 实例化构造方法是私有的对象
        NoneConstructor noneConstructor = (NoneConstructor) unsafe.allocateInstance(NoneConstructor.class);
        noneConstructor.show();


        // 实例化没有无参构造方法的对象
        ParamConstructor paramConstructor = (ParamConstructor) unsafe.allocateInstance(ParamConstructor.class);
        paramConstructor.show();
        // 给 paramConstructor 的私有实例变量 count 设置值
        Field count = paramConstructor.getClass().getDeclaredField("count");
        count.setAccessible(true);
        count.set(paramConstructor, 6);
        // 给 paramConstructor的public静态变量 NAME 设置值
        Field name = paramConstructor.getClass().getDeclaredField("NAME");
        name.set(paramConstructor, "施森林");
        paramConstructor.show();

        new Thread(() -> {
            System.out.println(ParamConstructor.NAME);
        }, "t1").start();

    }
}
